# from apps.ci.service.load_config import *
import configparser
import os
from base_server.diyMySql import *

class CiImpl(object):
    def __init__(self):
        self.DB = self.getConn()

    def getConn(self):
        config = configparser.ConfigParser()
        path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
        my_path = path + "/" + "conf/config.ini"
        config.read(my_path)
        host = config["ci"]["host"]
        username = config["ci"]["user"]
        password = config["ci"]["passwd"]
        database = config["ci"]["database"]
        print(host)
        dataBaseHandle = DataBaseHandle(host, username, password, database, port=3306)
        return dataBaseHandle



    def selectOne(self, id):
        sql = "SELECT * FROM ci_yapi WHERE id = %s"
        args = (id,)
        return self.DB.selectDb(sql, args)


    def selectAll(self):
        sql = "SELECT * FROM ci_yapi;"
        return self.DB.selectDb(sql)

    def insertOne(self,task_id,case_col,yapi_url):
        sql = "INSERT INTO ci_yapi (task_id, case_col, yapi_url) VALUES (%s, %s, %s)"
        args = (task_id,case_col,yapi_url,)
        self.DB.insertDB(sql, args)

    def delteOne(self,id):
        args = (id,)
        sql = """DELETE FROM ci_yapi WHERE id = %s;"""
        self.DB.deleteDB(sql, args)

    def update(self,id,task_id,case_col,yapi_url):
        args = (id,task_id, case_col, yapi_url)
        sql = "UPDATE ci_yapi SET task_id= %s, case_col =  %s, yapi_url = %s WHERE id = %s;"
        self.DB.updateDb(sql, args)


    def selectByTask_id(self, task_id):
        args = (task_id,)
        sql = "SELECT * FROM ci_yapi WHERE task_id = %s"
        result=self.DB.selectDb(sql, args)
        dict_head = ["id", "task_id", "case_col", "yapi_url"]
        dict = {}
        dict_list=[]
        if result[0]==1:
            for i in result[1]:
                dick_key = dict.fromkeys(dict_head,)
                dick_key["id"]=i[0]
                dick_key["task_id"] = i[1]
                dick_key["case_col"] = i[2]
                dick_key["yapi_url"] = i[3]
                dict_list.append(dick_key)
        import json
        dict = {"code": 0, "msg":"查询task和ci", "data":dict_list, "count":len(dict_list)}
        return json.dumps(dict,ensure_ascii=False)



if __name__ == '__main__':
    ci_impl = CiImpl()

